package com.bootdo.common.exception;

import com.bootdo.common.controller.BaseController;
import com.bootdo.log.domain.LogDO;
import com.bootdo.log.service.LogService;
import com.bootdo.common.utils.HttpServletUtils;
import com.bootdo.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class BDExceptionHandler extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    LogService logService;

    @ExceptionHandler({Exception.class})
    public Object handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        LogDO logDO = new LogDO();
        logDO.setGmtCreate(new Date());
        logDO.setOperation("error");
        logDO.setMethod(request.getRequestURL().toString());
        logDO.setParams(e.toString());
        logDO.setUserId(getLoginUserId(request));
        logDO.setUsername("TODO");
        logService.save(logDO);
        logger.error(e.getMessage(), e);

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");

        if (HttpServletUtils.jsAjax(request)) {
            return R.error(500, "服务器错误，请联系管理员");
        }
        return R.error(500, "服务器错误，请联系管理员");
    }
}
